<template>
    <component :is="renderComponent" :item="item" :selected-id="selectedId" @delete="handleDelete" />
</template>

<script setup>
    import { computed } from 'vue';
    import Swiper from './Swiper.vue'; // 假设你有这个轮播组件
    import News from './News.vue';
    import Notice from './Notice.vue';
    import Commodity from './Commodity.vue';
    import Menus from './Menus.vue';


    // 组件映射表
    const componentMap = {
        swiper: {
            component: Swiper,
            wrapper: true // 是否需要 t-card 包裹
        },
        news: {
            component: News, // 懒加载
            wrapper: true
        },
        notice: {
            component: Notice, // 懒加载
            wrapper: true
        },
        commodity: {
            component: Commodity, // 懒加载
            wrapper: false
        },
        menus: {
            component: Menus, // 懒加载
            wrapper: false
        },
    };

    const props = defineProps({
        item: {
            type: Object,
            required: true
        },
        selectedId: {
            type: Number,
            default: ''
        }
    });

    const emit = defineEmits(['delete']);

    // 根据 item.type 获取渲染组件
    const renderComponent = computed(() => {
        console.log(props.item.type)
        const cfg = componentMap[props.item.type] || {
            component: DefaultComponent,
            wrapper: false
        };
        return cfg.wrapper ? WrapperComponent(cfg.component) : cfg.component;
    });

    // 删除回调
    const handleDelete = (id, e) => {
        e.stopPropagation();
        emit('delete', id);
    };

    // 默认组件（兜底）
    const DefaultComponent = {
        props: ['item'],
        template: `<div>未知组件: {{ item.type }}</div>`
    };

    // 通用卡片包裹器
    function WrapperComponent(Comp) {
        return {
            props: ['item', 'selectedId'],
            emits: ['delete'],
            template: `
      <t-card class="component-card" :bordered="true" :title="item.title" :shadow="item.id === selectedId">
        <template #actions>
          <a href="javascript:void(0)" @click="$emit('delete', item.id, $event)" style="line-height: 24px">删除</a>
        </template>
        <template #default>
          <div class="component-body">
            <Comp :item="item" />
          </div>
        </template>
      </t-card>
    `,
            components: { Comp }
        };
    }
</script>

<style scoped>
    .component-card {
        height: 100%;
    }
    .component-body {
        height: calc(100% - 40px);
        overflow: hidden;
    }
</style>
